package com.probiz.estore.theme;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


public class TemplateViewResolver extends InternalResourceViewResolver {

    private static Map<String,String> viewTemplateMap =new HashMap<String,String>();
    public static String templatePrefix=null;

    /*
      * (non-Javadoc)
      *
      * @see org.springframework.web.servlet.view.InternalResourceViewResolver#buildView(java.lang.String)
      */
	@Override
	protected AbstractUrlBasedView buildView(String viewName) throws Exception {
		AbstractUrlBasedView view = super.buildView(viewName);
//		if (!AppContextUtil.getInstance().isFileExists(view.getUrl())) {
//			logger.error(new StringBuilder("Template not found: [").append(
//					view.getUrl()).append("]."));
//			return null;
//		}
		return view;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.springframework.web.servlet.view.UrlBasedViewResolver#getPrefix()
	 */
	@Override
	protected String getPrefix() {
        if(logger.isDebugEnabled()){
           logger.debug("prefix="+ TemplateUtil.getTemplatePrefix());
        }
        return TemplateUtil.getTemplatePrefix();

	}

    /*
	 * session里面的ts改变的话，需要重新createView而不能直接使用缓存的；可以判断是否与context里面的相同
	 *
	 * @see org.springframework.web.servlet.view.AbstractCachingViewResolver#resolveViewName(java.lang.String,
	 *      java.util.Locale)
	 */
	@Override
	public View resolveViewName(String viewName, Locale locale)
			throws Exception {
        String currentTemplatePrefix=TemplateUtil.getTemplatePrefix();
        if(currentTemplatePrefix.equals(viewTemplateMap.get(viewName))){
            return   super.resolveViewName(
				viewName, locale);
        }else{
           viewTemplateMap.put(viewName,currentTemplatePrefix);
           return createView(viewName, locale);
        }

	}

}

